<template>
  <view class="member-mian-container">
    <view class="comm-bootom-shadow">
      <view class="search-wrap">
        <view class="search-content">
          <view class="search-input-box no-base-sport">
            <input type="text" v-model="searchParams.keyword" class="search-input" placeholder="输入用户名" placeholder-style="color: #999" />
          </view>
          <view class="search-btn" @click="changeSearch">搜索</view>
        </view>
      </view>
      <view class="screen-wrap">
        <uni-data-select v-model="searchParams.roleType" :localdata="roleTypeOptions" @change="changeSearch" placeholder="用户类型"></uni-data-select>
      </view>
    </view>
    <scroll-view
      class="member-list"
      scroll-y="true"
      :refresher-enabled="true"
      @refresherrefresh="refresherrefresh"
      @refresherpulling="refresherpulling"
      :refresher-triggered="triggered"
      @scrolltolower="scrolltolower"
      :lower-threshold="30"
    >
      <template v-if="userList.length > 0">
        <view class="member-item common-card" v-for="(item, index) in userList" @click="goUserDetails(item)" :key="item.userId">
          <view class="user-basic">
            <view class="user-name">账号：{{ item.userName }}</view>
          </view>
          <view class="flex-center">
            <view>角色类型：{{ item.roleType == '0' ? '管理员' : '普通用户' }}</view>
            <view>昵称：{{ item.nickname || '未设置' }}</view>
          </view>
          <view class="flex-center">
            <view>邮箱：{{ item.email || '未设置' }}</view>
          </view>
          <view class="flex-center">
            <view>注册时间：{{ formatDate(item.createTime) }}</view>
          </view>
        </view>
      </template>
      <Empty v-if="userList.length == 0 && !isLoading"></Empty>
      <Loading v-if="isLoading"></Loading>
    </scroll-view>
  </view>
</template>

<script setup>
import Loading from "@/components/Loading/index.vue";
import Empty from "@/components/Empty/index.vue";
import { useUserStore } from "@/store/user";
import { reactive, ref, onMounted } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { getUserList } from "@/api/user";

const userStore = useUserStore();

// 搜索参数
const searchParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
  roleType: ''
});

// 角色类型选项
const roleTypeOptions = [
  { text: '全部', value: '' },
  { text: '管理员', value: '0' },
  { text: '普通用户', value: '1' }
];

// 用户列表数据
const userList = ref([]);
const listTotal = ref(0);
const isLoading = ref(false);
const triggered = ref(false);

// 下拉刷新
const refresherpulling = () => {
  triggered.value = true;
};

const refresherrefresh = async () => {
  changeSearch();
  triggered.value = false;
};

// 滚动加载更多
const scrolltolower = () => {
  if (listTotal.value > userList.value.length) {
    searchParams.pageNum += 1;
    getList();
  }
};

// 搜索
const changeSearch = () => {
  userList.value = [];
  searchParams.pageNum = 1;
  getList();
};

// 获取用户列表
const getList = async () => {
  isLoading.value = true;
  try {
    const res = await getUserList(searchParams);
    if (res.code === 200 && res) {
      if (searchParams.pageNum === 1) {
        userList.value = res.list || [];
      } else {
        userList.value = [...userList.value, ...(res.list || [])];
      }
      listTotal.value = res.total || 0;
    } else {
      uni.showToast({
        title: res.msg || '获取用户列表失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    uni.showToast({
      title: '获取用户列表失败',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '未知';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 跳转到用户详情
const goUserDetails = (item) => {
  uni.navigateTo({
    url: `/pages/question/components/userList/modules/userDetails?id=${item.userId}&roleType=${item.roleType}`,
  });
};

onShow(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.member-mian-container {
  width: 100%;
  background-color: $uni-primary-bg;
  height: 100vh;

  .search-wrap {
    padding-top: 10rpx;
  }
}

.member-list {
  height: calc(100% - 90rpx);
  padding: 20rpx 20rpx 20rpx;
  box-sizing: border-box;

  .member-item {
    padding: 20rpx;
    background-color: #fff;
    margin-bottom: 20rpx;
    display: flex;
    flex-direction: column;
    position: relative;

    & > view {
      margin-bottom: 10rpx;
    }

    .question-content {
      display: flex;

      & > view:first-child {
        width: 90rpx;
      }

      & > view:last-child {
        flex: 1;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
    }

    .star-wrap {
      position: absolute;
      right: 30rpx;
      bottom: 10rpx;
    }
  }
}

.screen-wrap {
  grid-template-columns: repeat(2, 1fr);
}

.text {
  height: 40rpx;
  line-height: 40rpx;
}

.flex-center {
  display: flex;
  align-items: center;

  & > view {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
